<template>
  <div id="app">
    <div id="amap"></div>
    <div class="content">
      <div>共有{{addressListSize}}条地址需要解析</div>
      <div>已解晰{{addressIndex}}条地址</div>
      <div>{{saveCount}}数据已存入数据库</div>
      <div>解析失败的地址</div>
      <ul>
        <li
          v-for="address of errorList"
          :id="address.id"
        >{{address.id}} - {{address.addr}} - {{address.code}} - {{address.name}}- {{address.province}} - {{address.city}} -{{address.district}}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import _service from "./service/address-serivce";
import _address from './service/address-serivce';

export default {
  name: 'app',
  data () {
    return {
      addressList: [],
      errorList: [],
      addressIndex: 0,
      geocoder: null,
      saveCount: 0
    }
  },
  computed: {
    addressListSize () {
      return this.addressList.length;
    }
  },
  mounted () {
    let _this = this;
    var map = new AMap.Map("amap", {
      resizeEnable: true
    });
    _service.getAllAddress(function (res) {
      res.forEach((value) => {
        _this.addressList.push(value);
      });
      _this.geocoder = new AMap.Geocoder();
      _this.resolveAddress();

    }, function (errMsg) {
      console.log(errMsg);
    });
  },
  methods: {
    resolveAddress () {
      const _this = this;
      if (this.addressIndex === this.addressListSize) {
        return;
      }
      let detailAddress = this.addressList[this.addressIndex].province + 
        this.addressList[this.addressIndex].city + this.addressList[this.addressIndex].district + this.addressList[this.addressIndex].addr;
      this.geocoder.setCity(this.addressList[this.addressIndex].city);
      this.geocoder.getLocation(detailAddress, function (status, result) {
        if (status === 'complete' && result.geocodes.length) {
          var lnglat = result.geocodes[0].location;
          let address = _this.addressList[_this.addressIndex];
          address.lng = lnglat.lng;
          address.lat = lnglat.lat;
          _address.updateLngLat({
            id: address.id,
            lng: address.lng,
            lat: address.lat
          }, function (res) {
            _this.saveCount++;
          }, function (errMsg) {
            console.log(errMsg);
          });

        } else {
          let address = _this.addressList[_this.addressIndex];
          _this.errorList.push(address);
        }
        _this.resolveAddress();
        _this.addressIndex++;
      });
    }
  }
}
</script>

<style lang="stylus" scoped>
#amap {
  width: 100%;
  height: 400px;
}

.content {
  padding-left: 20px;
  font-size: 20px;
}
</style>>
